package com.ying.core.filter;

import cn.dev33.satoken.stp.StpUtil;
import com.ying.core.exception.CustomException;
import com.ying.core.response.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Order(1)
@WebFilter(filterName = "loginFilter", urlPatterns = "/api/*")
public class LoginFilter implements Filter {

    private String[] excludedUris;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String param = filterConfig.getInitParameter("excludedUris");
        if (StringUtils.isNotBlank(param)) {
            this.excludedUris = param.split("\\s*,\\s*");
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 定义表示变量 并验证用户请求URI 是否包含不过滤路径
        boolean flag = false;
        for (String uri:excludedUris) {
            if (request.getRequestURI().equals(uri)){
                flag = true;
            }
        }
        if(flag){
            System.out.println("自定义过滤器filter,拦截url:"+request.getRequestURI());
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            if (StpUtil.isLogin()) {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
